import { Request, Response } from 'express'
import { PrismaClient } from '@prisma/client'
import axios from 'axios'
import FormData from 'form-data'

const prisma = new PrismaClient()

export class ImageController {
    // 获取图片列表
    async getImages(req: Request, res: Response) {
        try {
            const images = await prisma.image.findMany({
                include: {
                    user: true
                },
                orderBy: {
                    createdAt: 'desc'
                }
            })
            res.json(images)
        } catch (error) {
            res.status(500).json({ error: 'Failed to fetch images' })
        }
    }

    // 保存图片记录
    async saveImage(req: Request, res: Response) {
        try {
            const { title, prompt, url } = req.body

            // 获取或创建默认用户
            let user = await prisma.user.findFirst()
            if (!user) {
                user = await prisma.user.create({
                    data: {
                        email: 'default@example.com',
                        username: 'Default User',
                        avatar: 'https://via.placeholder.com/150'
                    }
                })
            }

            // 创建图片记录
            const image = await prisma.image.create({
                data: {
                    title,
                    prompt,
                    url,
                    userId: user.id
                },
                include: {
                    user: true
                }
            })

            res.json(image)
        } catch (error) {
            res.status(500).json({ error: 'Failed to save image' })
        }
    }

    // 分享图片
    async shareImage(req: Request, res: Response) {
        try {
            const { id } = req.params
            const image = await prisma.image.findUnique({
                where: { id },
                include: { user: true }
            })

            if (!image) {
                return res.status(404).json({ error: 'Image not found' })
            }

            // 这里可以实现分享逻辑，比如生成分享链接
            const shareUrl = `${process.env.FRONTEND_URL}/share/${id}`

            res.json({ shareUrl })
        } catch (error) {
            res.status(500).json({ error: 'Failed to share image' })
        }
    }
}